import request from './index'

// 上传单个文件
export function uploadFile(file, onProgress) {
  const formData = new FormData()
  formData.append('file', file)
  
  return request({
    url: '/upload/file',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    onUploadProgress: onProgress
  })
}

// 上传多个文件
export function uploadMultipleFiles(files, onProgress) {
  const formData = new FormData()
  files.forEach((file, index) => {
    formData.append(`files[${index}]`, file)
  })
  
  return request({
    url: '/upload/multiple',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    onUploadProgress: onProgress
  })
}

// 上传图片
export function uploadImage(file, onProgress) {
  const formData = new FormData()
  formData.append('image', file)
  
  return request({
    url: '/upload/image',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    onUploadProgress: onProgress
  })
}

// 上传视频
export function uploadVideo(file, onProgress) {
  const formData = new FormData()
  formData.append('video', file)
  
  return request({
    url: '/upload/video',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    onUploadProgress: onProgress
  })
}

// 删除文件
export function deleteFile(fileId) {
  return request({
    url: `/upload/files/${fileId}`,
    method: 'delete'
  })
}

// 获取文件信息
export function getFileInfo(fileId) {
  return request({
    url: `/upload/files/${fileId}`,
    method: 'get'
  })
}

// 获取用户文件列表
export function getUserFiles(params = {}) {
  return request({
    url: '/upload/user-files',
    method: 'get',
    params: {
      page: 1,
      limit: 20,
      ...params
    }
  })
}

// 检查文件类型
export function checkFileType(file) {
  const allowedImageTypes = import.meta.env.VITE_APP_ALLOWED_IMAGE_TYPES?.split(',') || 
    ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp']
  const allowedVideoTypes = import.meta.env.VITE_APP_ALLOWED_VIDEO_TYPES?.split(',') || 
    ['video/mp4', 'video/avi', 'video/mov', 'video/wmv', 'video/flv']
  
  if (allowedImageTypes.includes(file.type)) {
    return 'image'
  } else if (allowedVideoTypes.includes(file.type)) {
    return 'video'
  } else {
    return 'other'
  }
}

// 检查文件大小
export function checkFileSize(file, maxSize) {
  const defaultMaxSize = import.meta.env.VITE_APP_MAX_FILE_SIZE || 10 * 1024 * 1024 // 默认10MB
  const sizeLimit = maxSize || defaultMaxSize
  return file.size <= sizeLimit
}

// 压缩图片
export function compressImage(file, quality = 0.8, maxWidth = 1920) {
  return new Promise((resolve, reject) => {
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')
    const img = new Image()
    
    img.onload = () => {
      let { width, height } = img
      
      // 如果图片宽度超过最大宽度，按比例缩放
      if (width > maxWidth) {
        height = (height * maxWidth) / width
        width = maxWidth
      }
      
      canvas.width = width
      canvas.height = height
      
      try {
        ctx.drawImage(img, 0, 0, width, height)
        canvas.toBlob(blob => {
          if (blob) {
            // 保持原始文件名，但更改扩展名为jpg
            const fileName = file.name.replace(/\.[^/.]+$/, "") + '.jpg'
            resolve(new File([blob], fileName, { type: 'image/jpeg' }))
          } else {
            reject(new Error('图片压缩失败'))
          }
        }, 'image/jpeg', quality)
      } catch (error) {
        reject(error)
      }
    }
    
    img.onerror = () => {
      reject(new Error('图片加载失败'))
    }
    
    img.src = URL.createObjectURL(file)
  })
}